﻿using System;
using SAM.Framework.ILicence;
using SAM.Framework.ILicence.Models;
using SAM.Framework.Machine;
using SAM.Framework.Security;

namespace SAM.Framework.LicenceMico
{
    public class AuthorLicenceMicoService : IAuthorLicence
    {
        private ILicenceRepository licenceRepository;
        private IMachineProvider machineProvider;
        private ISecurity Security;
        private ILicenceUnescape licenceUnescape;

        public AuthorLicenceMicoService(ILicenceRepository licenceRepository,
            IMachineProvider machineProvider, ISecurity security, ILicenceUnescape licenceUnescape)
        {
            this.machineProvider = machineProvider;
            this.licenceRepository = licenceRepository;
            this.Security = security;
            this.licenceUnescape = licenceUnescape;
        }

        private MachineCodeInfo GetCode()
        {

            var machineInfo = this.machineProvider.GetMachineInfo();
            var codeInfo = new MachineTextCodeInfo()
            {
                Code = this.Security.SecurityTextForMd5(machineInfo.CpuNum + machineInfo.DiskNum + machineInfo.Mac)
            };
            return codeInfo;
        }

        public MachineCodeInfo Generate()
        {
            MachineCodeInfo codeInfo = this.GetCode();
            this.licenceRepository.Save(codeInfo);
            return codeInfo;
        }

        public T ReadAuthorizationInfo<T>() where T: AuthorizationInfo
        {
            return this.licenceRepository.ReadAuthorizationInfo<T>(); 
        }

        public T ReadMachineCodeInfo<T>() where T: MachineCodeInfo
        {
            return this.licenceRepository.ReadMachineCodeInfo<T>();
        }

        public bool Save(AuthorizationInfo authorizationInfo)
        {
            return this.licenceRepository.Save(authorizationInfo);
        }

        public bool Save(MachineCodeInfo machineCodeInfo)
        {
            return this.licenceRepository.Save(machineCodeInfo);
        }

        /// <summary>
        /// 逻辑逻辑
        /// 1. 机器码是否一致
        /// 2. 根据认证信息获取授权信息
        /// 3. 进行业务判断
        /// </summary>
        /// <returns></returns>
        public VerifyResult Verify()
        {
            VerifyResult result = new VerifyResult();

            MachineTextCodeInfo localMachineCodeInfo = this.ReadMachineCodeInfo< MachineTextCodeInfo>();
            MachineTextCodeInfo codeInfo = (MachineTextCodeInfo)this.GetCode();
            AuthorizationInfo authorizationInfo = this.ReadAuthorizationInfo<AuthorizationNormInfo>();
            LicenceInfo licenceInfo = this.licenceUnescape.Unescape(authorizationInfo);

            if ( localMachineCodeInfo.Code == codeInfo.Code && licenceInfo.ExpireDateTime.HasValue)
            {
                if(DateTime.Now <= licenceInfo.ExpireDateTime.Value)
                {
                    result.Expire = true;
                }
            }

            return result;
        }
    }
}
